package io.task.cc.message.socket;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;

@Slf4j
@Setter
@Getter
public class ByteBufferUtils {

    /**
     * 组合两个bytebuffer，把可读部分的组合成一个新的bytebuffer
     */
    public static ByteBuffer composite(ByteBuffer byteBuffer1, ByteBuffer byteBuffer2) {
        int capacity = byteBuffer1.remaining() + byteBuffer2.remaining();
        ByteBuffer ret = ByteBuffer.allocate(capacity);

        ret.put(byteBuffer1);
        ret.put(byteBuffer2);

        ret.position(0);
        ret.limit(ret.capacity());
        return ret;
    }


    /**
     * @param src        本方法不会改变position等指针变量
     * @param startindex 从0开始
     */
    public static ByteBuffer copy(ByteBuffer src, int startindex, int endindex) {
        int size = endindex - startindex;
        int initPosition = src.position();
        int initLimit = src.limit();

        src.position(startindex);
        src.limit(endindex);
        ByteBuffer ret = ByteBuffer.allocate(size);
        ret.put(src);
        ret.flip();

        src.position(initPosition);
        src.limit(initLimit);
        return ret;
    }

    /**
     * @param src 本方法不会改变position等指针变量
     */
    public static ByteBuffer copy(ByteBuffer src) {
        int startindex = src.position();
        int endindex = src.limit();
        return copy(src, startindex, endindex);
    }


}
